import sys
import random
import time

from PIL import Image, ImageDraw
import os

# import numpy

im = Image.open("feifei.bmp")
input_file = "feifei.bmp"

print('mode: ', im.mode)
print('size: ', im.size)
count = 0


def encode(input_file, output_file):
    im = Image.open(input_file)
    width, height = im.size

    out = Image.new('RGB', (width, height))  # 输出图像
    draw = ImageDraw.Draw(out)  # 画图
    lsb_data_cnt = 0

    payload_bin = open("payload_bin.txt", "r")  #  这里确定了需要被隐藏的数据
    cnt = 1
    for y in range(height):
        for x in range(width):
            pix = im.getpixel((x, y))  # 依次获取原图像素点
            print("变前：", end="")
            print(pix[0], pix[1], pix[2])  # 调试信息
            # pix_r = str(bin(pix[0]))[2:].zfill(8)  # 转换成二进制并转换为字符串并8位对齐
            # pix_g = str(bin(pix[1]))[2:].zfill(8)  # 转换成二进制并转换为字符串并8位对齐

            pix_b = str(bin(pix[2]))[2:].zfill(8)  # 转换成二进制并转换为字符串并8位对齐
            # print("lsb数据大小:" + str(len(data)))

            alt = payload_bin.read(1)  # 从变换文件中读取数据
            if alt == '':
                alt = str(random.randint(0, 1))  # 如果变换文件读完了就随机插入一个
            pix_b = pix_b[:7]  # 去b的掉最后一位
            pix_b = pix_b + alt  # 将变换文件的一位和前七位合并

            pix_b_int = int(pix_b, 2)
            print("变后：", end="")
            print(pix[0], pix[1], pix_b_int, end="")
            print(":" + str(cnt))
            cnt += 1

            co_list = list()
            co_list.append(pix[0])
            co_list.append(pix[1])
            co_list.append(pix_b_int)
            co_tuple = tuple(co_list)
            # print(co_list)
            # print(pix_list)
            draw.point((x, y), fill=co_tuple)  # 颜色元组，并且在（x,y）上画一个像素点
            out.save(output_file, 'bmp')


def read_bin(filename):
    f = open(filename, 'r')
    i = 0
    ch = "a"
    ret_list = list()  # 创建列表存储需要隐藏的数据
    while ch != '':
        ch = f.read(1)
        if ch != '':
            ch_int = int(ch, 16)  # 文件读取的变十进制
            ch_bin = bin(ch_int)  # 十进制变二进制
            ch_str = str(ch_bin)  # 二进制变字符串
            ch_str = ch_str[2:]  # 去0b
            ch_str_4 = ch_str.zfill(4)  # 补全四位
            # print(ch_str_4)
            ret_list.append(ch_str_4)
        else:
            print("end")
    return ret_list


lsb_list = read_bin('payload2_hex.txt')  # 将要隐写的图片的十六进制流变成二进制流


file_tmp = open('payload2_bin.txt', 'w')  # 清理缓存文件
file_tmp.close()
file_tmp = open('payload2_bin.txt', 'a+')
for i in lsb_list:
    file_tmp.write(i)
file_tmp.close()

# 62552 插入隐藏数据的位置
start_time = time.time()
encode(input_file, "lsb_2.bmp")  # 开始隐写
end_time = time.time()
print(end_time - start_time)
